#include "inputmethod.h"
#include <QDebug>
#include <QProcess>
#include <psapi.h>
InputMethod::InputMethod()
{
    hkl = LoadKeyboardLayoutA("0x0409", KLF_ACTIVATE); //EN
}

void InputMethod::checkAndSetEn()
{
    HWND hwnd = GetForegroundWindow();
    if (lastHwnd == hwnd) return;
    QString title = getWindowTitle(hwnd);
    QString processName = getProcessNameByPID(getForeWindowPID(hwnd));

    qDebug() << title << processName;

    if (isWindowTitleInList(title) || isProcessNameInList(processName))
        setEnMode(hwnd);
    lastHwnd = hwnd;
}

void InputMethod::setList(const QStringList& strList)
{
    list = strList;
}

bool InputMethod::isWindowTitleInList(const QString& title)
{
    for (const QString& str : list)
        if (!str.contains(".exe") && title.contains(str, Qt::CaseInsensitive))
            return true;
    return false;
}

bool InputMethod::isProcessNameInList(const QString& name)
{
    for (const QString& str : list)
        if (name == str)
            return true;
    return false;
}

DWORD InputMethod::getForeWindowPID(HWND hwnd)
{
    if (hwnd == NULL)
        hwnd = GetForegroundWindow();
    DWORD processId = -1; //not NULL
    GetWindowThreadProcessId(hwnd, &processId);
    return processId;
}

QString InputMethod::getProcessNameByPID(DWORD PID)
{
    static WCHAR path[512];
    HANDLE Process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, PID);
    GetProcessImageFileNameW(Process, path, _countof(path)); //not sizeof
    CloseHandle(Process);

    QString pathS = QString::fromWCharArray(path);
    return pathS.mid(pathS.lastIndexOf('\\') + 1);

    /*QProcess process;
    process.start("tasklist", QStringList() << "/FI" << QString("PID eq %1").arg(PID) << "/FO"
                                            << "CSV"
                                            << "/NH");
    process.waitForFinished();// --------------------------------------------------------------------######阻塞UI######
    QString res = process.readAllStandardOutput();
    QStringList resList = res.simplified().split(",");
    return resList[0].replace("\"", "");*/
}

QString InputMethod::getWindowTitle(HWND hwnd)
{
    static WCHAR title[256];
    if (hwnd == NULL)
        hwnd = GetForegroundWindow();
    GetWindowTextW(hwnd, title, _countof(title)); //not sizeof
    return QString::fromWCharArray(title); //解决中文乱码
}

void InputMethod::setEnMode(HWND hwnd)
{
    PostMessageA(hwnd, WM_INPUTLANGCHANGEREQUEST, (WPARAM)TRUE, (LPARAM)hkl);
    qDebug() << "#set EN++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
}
